package com.common.frame.mvp.base;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import java.lang.ref.SoftReference;

import io.reactivex.disposables.CompositeDisposable;


public class BasePresenter<V extends IView> implements IPresenter<V> {

    public CompositeDisposable mCompositeSubscription = new CompositeDisposable();

    /**
     * view 的软引用,当内存不足释放内存
     */
    protected SoftReference<V> mViewRef;

    public void attachView(LifecycleOwner owner, V view){
        mViewRef = new SoftReference<>(view);
        if (owner != null){
            owner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
                if (event == Lifecycle.Event.ON_DESTROY){
                    onDestroy();
                }
            });
        }
    }

    /**
     * 获取view的方法
     *
     * @return 当前关联的view
     */
    public V getView() {
        if (mViewRef == null){
            return null;
        }
        return mViewRef.get();
    }

    @Override
    public void onDestroy() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        mCompositeSubscription.dispose();
    }
}
